<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Middleware\JwtMiddleware;
use App\Model\VerifyCode;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

#[Controller]
class VerifyCodeController
{
    #[Inject]
    protected RequestInterface $request;

    #[RequestMapping(path: "send", methods: "post")]
    /**
     * 列表
     * @return false|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function send()
    {
        $code = rand(100000, 999999);
        $mobile = $this->request->input('mobile');
        if (!$mobile) {
            return self::jsonResponse(422, '请填写手机号');
        }

        $verifyCode = new VerifyCode();
        $verifyCode->send($code, $mobile);
        $verifyCode->save();

        return self::jsonResponse(200, 'success');
    }

    #[RequestMapping(path: "verify", methods: "post")]
    /**
     * 详情
     * @return false|string
     */
    public function verify()
    {
        $code = $this->request->input('code');
        if (!$code) {
            return self::jsonResponse(422, '请填写验证码');
        }

        //临时万能验证码
        if ($code == '999999') {
            return self::jsonResponse(200, 'success');
        }

        $mobile = $this->request->input('mobile');
        if (!$mobile) {
            return self::jsonResponse(422, '获取手机号失败');
        }

        $verifyCode = VerifyCode::query();
        $verifyCode->active();
        $verifyCode->where(['code' => $code, 'mobile' => $mobile]);
        $verifyCode = $verifyCode->first();
        if (!$verifyCode) {
            return self::jsonResponse(400, '验证码错误');
        }

        return self::jsonResponse(200, 'success');
    }

    public static function jsonResponse(int $status = 1, $message = 'success', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'success';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return json_encode(['status' => $status, 'message' => $message, 'data' => $data]);

//        return response()->json(
//            ['status' => $status, 'message' => $message, 'data' => $data],
//            $headerStatus,
//            [],
//            JSON_UNESCAPED_UNICODE
//        );
    }
}
